package com.LeeCode;

import java.util.Stack;

/**
 * 有效括号
 */

public class Code020 {
    public static void main(String[] args) {
        String s = "(){}}{";
        boolean res = new Code020().isValid(s);
        System.out.println(res);

    }

    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        stack.push(s.charAt(0));
        int index = 1;

        while (index < s.length()) {
            char c = s.charAt(index);
            if (c == '(' || c == '[' || c == '{') {
                stack.push(c);
            } else {

                if (stack.isEmpty()) {
                    return false;
                }

                char pop = stack.pop();
                if (c == ')' && pop != '(') {
                    return false;
                }else if (c == ']' && pop != '[') {
                    return false;
                }else if (c == '}' && pop != '{') {
                    return false;
                }
            }
            index++;
        }
        return stack.isEmpty();
    }
}
